<?PHP
//Die if security key not defined. This prevents malisious usage.
if(!defined('URLFZ'))
	die('Hacking Attempt');

//Takes in an int and string(a list of characters) and returns a string representing the integer using only characters found in the string
function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS){	
	$base = utf8_decode($base);
	$length = strlen($base);
	while($integer > $length - 1)
	{
		$out = $base[fmod($integer, $length)] . $out;
		$integer = floor( $integer / $length );
	}
	return utf8_encode($base[$integer] . $out);
}

//Just returns the url Nothing special allows testing outside of server enviroment
getURL(){
	return trim($_REQUEST['longurl']);
}

//returns just the protocol or empty string on err
function filterProtocal($url){
	$protocol = preg_replace('/^(([a-zA-Z]){1,6}:\/\//)(.)*/','$2',$url);
	if(empty($protocol))
		$protocol = 'http://';
	return $protocol;
}
//returns just the domain or empty string on err
function filterDomain($url){
	$domain = preg_replace('/^([a-zA-Z]){1,6}:\/\//([a-zA-Z0-9_\.-])/','$2',$url);
	return $domain;
}

// returns just the path or empty string on err
function filterPath($url){
	$path = '/' . preg_replace('/^([a-zA-Z]){1,6}:\/\//[a-zA-Z0-9_\.-](/[^?]*)','$2',$url);
	return $path;
}

//returns just the query or empty string on err
function filterQuery($url){
	$query = '?' . preg_replace('/(\?.*)$/', '$1', $url);
	return $query;
}
/*
function checkURLexists($url){
	if(CHECK_URL){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch,  CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_NOBODY, TRUE); // only request HTTP header
		curl_exec($ch);
		$code = floor(curl_getinfo($ch, CURLINFO_HTTP_CODE)/100);
		curl_close($ch);
		if( $code != '2' && $code != '3'){
			die('Invalad URL: Non Existant');
		}
	}
	return url;
}
*/
function checkURLexists($url){
	if(CHECK_URL){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch,  CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_NOBODY, TRUE); // only request HTTP header
	curl_exec($ch);
	$code = floor(curl_getinfo($ch, CURLINFO_HTTP_CODE)/100);
	curl_close($ch);
//	if ( rec < 2 ){
//		checkURLexists(CURLINFO_EFFECTIVE_URL, $rec + 1);
//	}else
if( $code != '2' && $code == '3'){
		die('Invalad URL: Non Existant');
	}
	}
}

function verifyRecaptcha($challenge, $response){
	if(RECAPTCHA){
		$resp = recaptcha_check_answer(RE_PRI_KEY, REMOTE_ADDR,$challenge, $response);
		if (!$resp->is_valid){
			die('Bad Captcha');
		}
	}
}

//check url against a list of blacklisted sites
function checkBlacklist($url){
	global $config;
	$sites = implode(')|(', $config['blacklist']);
	if(preg_match('/('. preg_replace('/\./', '\\\.',$sites) .')/', strtolower($url))){
		die('Invalad URL: Site Blacklisted');
		}
}

?>
